from .models import User
from schools.models import School


def front_user_middleware(get_response):
    def middleware(request):
        # request到达view之前的中间件代码
        user_phone = request.session.get('user_phone')
        if user_phone:
            user = User.objects.filter(css_phone=user_phone).first()
            school = School.objects.filter(css_phone=user_phone).first()
            if user:
                request.front_user = user
            elif school:
                request.front_user = school
            else:
                request.front_user = None
        else:
            request.front_user = None
        response = get_response(request)
        # response到达浏览器之前的代码
        return response
    return middleware
